#!/usr/bin/env python
# encoding: utf-8
# @Time : 2020/6/22 8:06 
# @Author : 能量咖啡豆 
# @File : linereg.py.py 
# @desc : 线性回归实践
import numpy as np
import matplotlib.pyplot as plt
"""
# 读取文件
# dataMat输入变量
# labelMat输出变量
"""
def loadDataSet(fileName):
    numFeat = len(open(fileName).readline().split('\t')) - 1
    dataMat = []
    labelMat = []

    fr = open(fileName)
    for line in fr.readlines():
        lineArr = []
        curLine = line.strip().split('\t')
        for i in range(numFeat):
            lineArr.append(float(curLine[i]))
        dataMat.append(lineArr)
        labelMat.append(float(curLine[-1]))
    return dataMat, labelMat

"""
# 求最佳拟合直线
"""
def standRegres(xArr, yArr):
    xMat = np.mat(xArr)
    yMat = np.mat(yArr).T
    xTx = xMat.T * xMat
    if np.linalg.det(xTx) == 0.0:
        print("This matrix is singular, cannot do inverse")
        return
    ws = xTx.I * (xMat.T*yMat)
    return ws


if __name__ == "__main__":
    print("linear regression")
    #计算w，回归系数
    xArr, yArr = loadDataSet('data/ex0.txt')
    ws = standRegres(xArr, yArr)
    xMat = np.mat(xArr)
    yMat = np.mat(yArr)
    yHat = xMat * ws

    #绘图
    fig = plt.figure()
    ax = fig.add_subplot(111)

    #绘制点
    ax.scatter(xMat[:,1].flatten().A[0], yMat.T[:,0].flatten().A[0])

    #绘制预测直线
    xCopy = xMat.copy()
    xCopy.sort(0)
    yHat = xCopy * ws
    ax.plot(xCopy[:,1], yHat)

    plt.show()

    #计算相关性，如果没猜错，这块应该算的是方差
    yHat = xMat * ws
    per = np.corrcoef(yHat.T, yMat)
    print(per)


